{% extends 'admin/base.html' %}
{% load static %}

{% block title %}工程信息{% endblock %}
{% block css %}
<link href="{% static 'vendor/datatables/dataTables.bootstrap4.min.css' %}" rel="stylesheet">
<link href="{% static 'js/editor/css/style.css' %}" rel="stylesheet">
<style>
    .modal-dialog {
        max-width: 1400px;
    }
    .text-ellipsis {
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
        max-width: 100%;
    }
    .text-ellipsis-multiline {
        display: -webkit-box;
        -webkit-line-clamp: 3;
        -webkit-box-orient: vertical;
        overflow: hidden;
        text-overflow: ellipsis;
    }
    #editor-wrapper {
        border: 1px solid #ccc;
        z-index: 100;
    }
    #toolbar-container {
        border-bottom: 1px solid #ccc;
    }
    #editor-container {
        height: 500px; /* 修改内容编辑器的高度 */
    }
    #image_preview {
        cursor: pointer;
        max-width: 150px; /* 设置预览图片的高度 */
        max-height: 100px; /* 设置预览图片的高度 */
    }
</style>
{% endblock %}
{% block pagecontent %}
<h1 class="h3 mb-2 text-gray-800 mb-2">工程管理</h1>

<div class="card shadow mb-4">
    <div class="card-header" style="text-align: end">
        <button class="btn btn-dark btn-sm" id="add_news" data-toggle="modal" data-target="#AddModal">
            <a href="javascript:void(0);" style="color: #ffffff; text-decoration: none">添加工程</a>
        </button>
    </div>
    <div class="card-body">
        <div class="table-responsive">
            <table class="table table-sm table-striped" id="NewsTable" width="100%" cellspacing="0">
                <thead>
                    <tr>
                        <th style="width: 15%">标题</th>
                        <th style="width: 15%">发布时间</th>
                        <th style="width: 60%" class="text-ellipsis">内容</th>
                        <th style="width: 10%">操作</th>
                    </tr>
                </thead>
                <tbody>
                </tbody>
            </table>
        </div>
    </div>
</div>

<div class="modal fade" id="AddModal" tabindex="-1" role="dialog" aria-labelledby="AddLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="AddLabel">添加工程</h5>
                <button type="button class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <div class="container-fluid">
                    <div class="row mb-3 align-items-center">
                        <div class="col-md-5">
                            <label for="news_title" class="col-form-label">标题</label>
                            <input type="text" class="form-control" placeholder="工程标题" id="news_title" required>
                        </div>
                        <div class="col-md-2">
                            <label for="publish_date" class="col-form-label">发布日期</label>
                            <input type="date" class="form-control" id="publish_date" required>
                        </div>
                        <div class="col-md-3">
                            <label for="cover_image" class="col-form-label">封面图片</label>
                            <input type="file" class="form-control-file" id="cover_image" accept="image/*"
                                onchange="previewImage();">
                        </div>
                        <div class="col-md-2">
                            <img id="image_preview" src="{% static 'img/xibao.png' %}" alt="点击查看封面图片"
                                onclick="viewFullImage(this.src)">
                        </div>
                    </div>

                    <div class="input-group col-md-12 row mb-3">
                        <label class="col-sm-2 col-form-label">内容</label>
                        <div id="editor-wrapper" style="width: 100%;">
                            <div id="toolbar-container"></div>
                            <div id="editor-container"></div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-primary btn-sm" id="saveButton" onclick="submit_news()">保存</button>
                <button type="button" class="btn btn-primary btn-sm" id="updateButton" style="display: none;"
                    onclick="update_news()">修改</button>
                <button type="button" class="btn btn-sm" data-dismiss="modal">取消</button>
            </div>
        </div>
    </div>
</div>

<!-- 用于显示大图的模态框 -->
<div class="modal fade" id="ImageModal" tabindex="-1" role="dialog" aria-labelledby="ImageLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="ImageLabel">查看图片</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body text-center">
                <img id="full_image" src="" alt="图片预览" style="max-width: 100%;">
            </div>
        </div>
    </div>
</div>
{% endblock %}
{% block scripts %}
<script src="{% static 'vendor/datatables/jquery.dataTables.min.js' %}"></script>
<script src="{% static 'vendor/datatables/dataTables.bootstrap4.min.js' %}"></script>
<script src="{% static 'js/editor/index.js' %}"></script>
<script>
    // 全局变量
    let isEditMode = false;
    let currentNewsId = null;
    let table;
    let originalCoverImageUrl = null; // 用于存储原始封面图片URL

    function getCSRFToken() {
        let name = "csrftoken";
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }

    function formatDate(isoDateStr) {
        const date = new Date(isoDateStr);
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        return `${year}-${month}-${day}`;
    }

    function resetForm() {
        $('#news_title').val('');
        window.editorInstance.clear();
        $('#publish_date').val(new Date().toISOString().split('T')[0]);
        $('#cover_image').val('');

        // 设置默认封面图片
        const imgElement = document.getElementById('image_preview');
        imgElement.src = '{% static "img/xibao.png" %}'; // 默认封面图片路径
        imgElement.style.display = 'block';

        isEditMode = false;
        currentNewsId = null;
        originalCoverImageUrl = null;
        $('#saveButton').show();
        $('#updateButton').hide();
    }

    function submit_news() {
        let title = $('#news_title').val(),
            content = window.editorInstance.getHtml(),
            publishDate = $('#publish_date').val();

        const coverImage = document.getElementById('cover_image').files[0];

        if (coverImage) {
            const formData = new FormData();
            formData.append('file', coverImage);

            $.ajax({
                url: "/api/news/upload/",
                type: "POST",
                data: formData,
                processData: false,
                contentType: false,
                success: function (response) {
                    const coverImageUrl = response.data[0].url;
                    postNewsData(title, content, publishDate, coverImageUrl);
                },
                error: function () {
                    alert("图片上传失败");
                }
            });
        } else {
            postNewsData(title, content, publishDate, '/static/img/xibao.png');
        }
    }

    function postNewsData(title, content, publishDate, coverImageUrl) {
        $.ajax({
            url: "/console/news/add/",
            type: "POST",
            data: JSON.stringify({
                title: title,
                content: content,
                publish_date: publishDate,
                cover_image_url: coverImageUrl,
                type: 'project_update'  // 添加 type 字段
            }),
            contentType: "application/json; charset=utf-8",
            success: function () {
                $('#AddModal').modal('hide');
                alert("工程已成功添加");
                table.ajax.reload(); // 刷新DataTable的数据
                resetForm();
            },
            error: function () {
                alert("创建工程时发生错误");
            }
        });
    }

    function update_news() {
        let title = $('#news_title').val(),
            content = window.editorInstance.getHtml(),
            publishDate = $('#publish_date').val();

        const coverImage = document.getElementById('cover_image').files[0];

        if (coverImage) {
            const formData = new FormData();
            formData.append('file', coverImage);

            $.ajax({
                url: "/api/news/upload/",
                type: "POST",
                data: formData,
                processData: false,
                contentType: false,
                success: function (response) {
                    const coverImageUrl = response.data[0].url;
                    putNewsData(title, content, publishDate, coverImageUrl);
                },
                error: function () {
                    alert("图片上传失败");
                }
            });
        } else {
            const imageUrl = originalCoverImageUrl || '/static/img/xibao.png';
            putNewsData(title, content, publishDate, imageUrl);
        }
    }

    function putNewsData(title, content, publishDate, coverImageUrl) {
        $.ajax({
            url: "/api/news/update/" + currentNewsId + "/",
            type: "PUT",
            data: JSON.stringify({
                title: title,
                content: content,
                publish_date: publishDate,
                cover_image_url: coverImageUrl,
                type: 'project_update' 
            }),
            contentType: "application/json; charset=utf-8",
            success: function () {
                $('#AddModal').modal('hide');
                alert("工程已成功更新");
                table.ajax.reload(); // 刷新DataTable的数据
                resetForm();
            },
            error: function () {
                alert("更新工程时发生错误");
            }
        });
    }

    function delete_news(newsId) {
        if (confirm("确认是否删除该工程")) {
            $.ajax({
                url: "/api/news/delete/" + newsId + "/",
                type: "DELETE",
                success: function () {
                    table.ajax.reload();
                    alert("工程已删除");
                },
                error: function () {
                    alert("删除失败");
                }
            });
        }
    }

    function edit_news(newsId) {
        $.get("/api/news/" + newsId + "/", function (data) {
            console.log('data数据', data);

            isEditMode = true;
            currentNewsId = newsId;

            $('#saveButton').hide();
            $('#updateButton').show();

            $('#news_title').val(data.title);

            if (window.editorInstance) {
                window.editorInstance.setHtml(data.content);
            } else {
                console.error('Editor instance is not available.');
            }

            $('#publish_date').val(formatDate(data.publish_date));

            if (data.cover_image_url) {
                originalCoverImageUrl = data.cover_image_url; // 保存原始封面图片URL
                const imgElement = document.getElementById('image_preview');
                imgElement.src = data.cover_image_url;
                imgElement.style.display = 'block';
            } else {
                originalCoverImageUrl = null; // 没有原始图片
                document.getElementById('image_preview').src = '{% static "img/xibao.png" %}';
            }

            $('#AddModal').modal('show');
        });
    }

    function previewImage() {
        const file = document.getElementById('cover_image').files[0];
        const reader = new FileReader();

        reader.onloadend = function () {
            const imgElement = document.getElementById('image_preview');
            imgElement.src = reader.result;
            imgElement.style.display = 'block';
        };

        if (file) {
            reader.readAsDataURL(file);
        } else {
            const defaultImg = '{% static "img/xibao.png" %}';
            const imgElement = document.getElementById('image_preview');
            imgElement.src = defaultImg;
        }
    }

    function viewFullImage(src) {
        $('#full_image').attr('src', src);
        $('#ImageModal').modal('show');
    }

    $(document).ready(function () {
        const initialUrl = "/api/news/list/";

        table = $('#NewsTable').DataTable({
            "processing": true,
            "serverSide": true,
            "ajax": {
                url: initialUrl,
                type: "GET",
                dataType: "json",
                data: function (d) {
                    d.type = 'project_update'; // 默认加载工程信息
                    return d;
                },
                dataSrc: function (json) {
                    json.recordsTotal = json.count;
                    json.recordsFiltered = json.count;
                    return json.results;
                }
            },
            "paging": true,
            "lengthChange": false,
            "pageLength": 10,
            "searching": false,
            "ordering": false,
            "language": {
                "sZeroRecords": "没有数据！",
                "sEmptyTable": "当前未查询到信息",
                "sInfo": "当前显示 _START_ 到 _END_ 条，共 _TOTAL_ 条记录",
                "sInfoEmpty": "显示0到0条记录",
                "sProcessing": '<i class="fa fa-spinner fa-pulse fa-2x fa-fw"></i>\n' +
                    '<span class="sr-only">Loading...</span>',
                "oPaginate": {
                    "sFirst": "首页",
                    "sPrevious": "上页",
                    "sNext": "下页",
                    "sLast": "末页"
                }
            },
            "columns": [
                { "data": 'title' },
                {
                    "data": 'publish_date',
                    "render": function (data) {
                        return formatDate(data);
                    }
                },
                {
                    "data": 'content',
                    "render": function (data) {
                        return '<div class="text-ellipsis-multiline">' + data + '</div>';
                    }
                },
                {
                    "data": {},
                    "render": function (data) {
                        return `<a href="javascript:void(0);" style="text-decoration: none" onclick="edit_news('${data['id']}')">编辑</a>&nbsp;` +
                            `<a href="javascript:void(0);" style="text-decoration: none" onclick="delete_news('${data['id']}')">删除</a>`;
                    }
                }
            ]
        });

        $('#add_news').click(function () {
            resetForm();
        });

        var today = new Date().toISOString().split('T')[0];
        $('#publish_date').val(today);

        $('#collapseNews').collapse('show');
        $('a[href="/console/project_updates"]').addClass('active');

        // 初始化WangEditor
        const { createEditor, createToolbar } = window.wangEditor;

        const editorConfig = {
            placeholder: '请输入内容...',
            onChange(editor) {
                const html = editor.getHtml();
                console.log('Editor content', html);
                // 可以将内容同步到隐藏的textarea或其他地方
            }
        };

        const editor = createEditor({
            selector: '#editor-container',
            html: '<p><br></p>',
            config: editorConfig,
            mode: 'default'
        });

        const toolbarConfig = {};

        const toolbar = createToolbar({
            editor,
            selector: '#toolbar-container',
            config: toolbarConfig,
            mode: 'default'
        });

        // 将editor实例存储到全局以便其他函数调用
        window.editorInstance = editor;
    });
</script>
{% endblock %}